<template>
  <div class="tableRow">
    <el-row class="select-list" v-permission="'bus:data:query'">
        <h4 class="textCenter">{{ models.structure.title }}</h4>
        <h2 class="textCenter">{{ models.structure.subTitle }}</h2>
    </el-row>
    <el-row class="select-list" v-permission="'bus:data:query'">
        <br/>
        <br/>
        <h3 class="textCenter">{{ models.structure.monthId.substring(0,4) +'年' +models.structure.monthId.substring(5) +'月'  }}</h3>
    </el-row>

    <el-row class="select-list" v-permission="'bus:data:query'">
        <br/>
        <br/>
        <h3 class="textCenter">{{ models.common.title }}</h3>
    </el-row>
 
        <el-row class="select-list" v-permission="'bus:data:query'">
            <br/>
            <br/>
            <template  v-if="models.common.headCode && models.common.headCode.length > 0">
                <el-row class="headerTitle"  v-for="(code,index) in models.common.headCode" :key="index">
                    <el-input v-model="models.surveyForm[code.name]" @change="findOriginData" @blur="findOriginData" :placeholder="code.label" style="width:100%;margin-left: 20px;" size="small" clearable >
                        <template slot="prepend"><span class="inputLabel">{{ code.label }} ：</span></template>
                    </el-input>
                </el-row>
            </template>
         
        </el-row>
        <el-table :data="models.common.common" style="width: 100% ;height:100%" :header-cell-style="{background:'#DCDFE6'}" highlight-current-row>
            <el-table-column prop="code" label="代码" width="180" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.contentType ==='-'" class="textCenter" >
                        {{scope.row.code}}
                    </span>
                    <el-tag  v-else type="success">{{scope.row.code}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="指标名称" width="260" header-align="center" align="left">
                <template slot-scope="scope">
                    <span v-if="scope.row.code =='——'"><h4>{{scope.row.name }}</h4></span>
                    <el-tag  v-else type="success">{{scope.row.name}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="investData" label="普查数据" width="260" align="left">
                <template slot-scope="scope">
                    <span v-if="scope.row.contentType ==='-'" class="textCenter" >{{scope.row.investText }}</span>
                    <span v-else-if="deduceCodeType(scope.row.contentType,scope.row.inputCode,'0')">
                        <el-input disabled v-model="models.surveyForm.investData[scope.row.inputCode]" :placeholder="scope.row.name" size="small" clearable />
                    </span>
                    <div v-else-if="deduceCodeType(scope.row.contentType,scope.row.inputCode,'1')">
                        <el-checkbox-group 
                                v-model="models.surveyFormArr.investData[scope.row.inputCode] "
                                :max=1
                                size="mini"
                                >
                                <el-checkbox disabled v-for="city in scope.row.investCategory" :label="city" :key="city">{{city}}</el-checkbox>
                        </el-checkbox-group>
                    </div>
                    <div v-else-if="deduceCodeType(scope.row.contentType,scope.row.inputCode,'2')">
                        <el-checkbox-group 
                                v-model="models.surveyFormArr.investData[scope.row.inputCode] "
                                size="mini"
                                >
                                <el-checkbox disabled v-for="city in scope.row.investCategory" :label="city" :key="city">{{city}}</el-checkbox>
                        </el-checkbox-group>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="updateData" class="inputLable" label="更新数据" width="260" align="left">
                <template slot-scope="scope">
                    <span v-if="scope.row.contentType ==='-'" class="textCenter">{{scope.row.updateText }}</span>
                    <span v-else-if="scope.row.contentType ==='0'" >
                        <el-input v-model="models.surveyForm.updateData[scope.row.inputCode]" :placeholder="scope.row.name" size="small" clearable />
                    </span>
                    <div v-else-if="scope.row.contentType === '1'" class="inputLabel">
                        <el-checkbox-group 
                                v-model="models.surveyFormArr.updateData[scope.row.inputCode] "
                                :max="1"
                                size="mini"
                                text-color="#67C23A"
                                >
                                <el-checkbox v-for="city in scope.row.updateCategory" :label="city" :key="city">{{city}}</el-checkbox>
                        </el-checkbox-group>
                    </div>
                    <div v-else-if="scope.row.contentType === '2'" class="inputLabel">
                        <el-checkbox-group 
                                v-model="models.surveyFormArr.updateData[scope.row.inputCode] "
                                size="mini"
                                text-color="#67C23A"
                                >
                                <el-checkbox v-for="city in scope.row.updateCategory" :label="city" :key="city">{{city}}</el-checkbox>
                        </el-checkbox-group>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="unit" label="计量单位" width="180" align="center">
                <template slot-scope="scope">
                    <el-tag type="warning">{{scope.row.unit}}</el-tag>
                </template>
            </el-table-column>
        </el-table>
        <el-row class="select-list" v-permission="'bus:data:query'">
            <template v-if="models.common.endCode && models.common.endCode.length > 0" >
            <el-row>
                <br/>
                <br/>
                <el-col :span="8" v-for="(code,index) in models.common.endCode" :key="index">
                        <el-input  v-model="models.surveyForm[code.name]" :placeholder="code.label" st size="small" clearable >
                            <template slot="prepend"><span class="inputLabel">{{code.label }}：</span></template>
                        </el-input>
                </el-col>
            </el-row>
            </template>
        </el-row>
        <br/>
        <br/>
        <br/>
        <div v-if="models.dynamic.id">
            <el-row class="select-list" v-permission="'bus:data:query'">
                <br/>
                <br/>
                <h3 class="textCenter">{{ models.dynamic.title }}</h3>
            </el-row>
            <el-row class="select-list" v-permission="'bus:data:query'">
            <br/>
            <br/>
            <template  v-if="models.dynamic.headCode && models.dynamic.headCode.length > 0">
                <el-row class="headerTitle"  v-for="(code,index) in models.dynamic.headCode" :key="index">
                    <el-input v-model="models.dynamicForm[code.name]" @change="findOriginData" @blur="findOriginData" :placeholder="code.label" style="width:100%;margin-left: 20px;" size="small" clearable >
                        <template slot="prepend"><span class="inputLabel">{{ code.label }} ：</span></template>
                    </el-input>
                </el-row>
            </template>
            <el-row class="select-list">
           
            </el-row>
            <el-row class="select-list" v-permission="'bus:data:query'">
            <template v-if="models.dynamic.endCode && models.dynamic.endCode.length > 0" >
            <el-row>
                <br/>
                <br/>
                <el-col :span="8" v-for="(code,index) in models.dynamic.endCode" :key="index">
                        <!-- <el-date-picker v-if="code.label.includes('日期')" v-model="surveyFormModel[code.name]"  type="date" :placeholder="code.label" :picker-options="pickerOptions">
                        </el-date-picker>
                        <el-input v-else-if="code.label.includes('说明')" type="textarea" :rows="1" v-model="surveyFormModel[code.name]" :placeholder="code.label" st size="small" clearable >
                            <template slot="prepend">{{code.label }}：</template>
                        </el-input> -->
                        <el-input  v-model="models.dynamicForm[code.name]" :placeholder="code.label" st size="small" clearable >
                            <template slot="prepend"><span class="inputLabel">{{code.label }}：</span></template>
                        </el-input>
                </el-col>
            </el-row>
            </template>
        </el-row>
        </el-row>
        </div>
      

        <br/>
    <el-row class="select-list" v-permission="'bus:data:query'">
       
        <el-col :span="6"><div class="grid-content" style="float: right;margin-top: 5px;color: #E6A23C;">
            如果指定区域请选择这里：
         </div>
       </el-col>
        <el-col :span="8"><div class="grid-content ">
            <el-tree-select v-model="models.surveyForm.areaId" :selectParams="options.selectParams"
                            :treeParams="options.treeParams" 
                            @searchFun="searchAreaFun" ref="areaTreeSelect"/>
        </div></el-col>
        <el-col :span="8"><div class="grid-content ">
            <el-button type="success" icon="el-icon-s-promotion" size="large" plain @click="handleSubmit"
            v-permission="'bus:servy:add'"> 提交</el-button>
        </div></el-col>
    </el-row>
  </div>
</template>
<script lang="ts">
import { Component, Vue,Ref } from 'vue-property-decorator';
import router from '@/router/index';
import {
    getStructureById
} from '@/api/investStructure';
import {
    surveyByStructureId,
    queryLastData
} from '@/api/investSubStructure';

import{userAreaTreeSelectData} from '@/api/area';
import TreeSelect from '@/components/TreeSelect.vue';
import commonSurveyStr from '@/utils/commonSurveyStr';
import commonSurveyArr from '@/utils/commonSurveyArr';
import {addFromOnline } from '@/api/investDataCommon'
@Component({ components: { TreeSelect} })
export default class Survey extends Vue{

    @Ref("areaTreeSelect") areaTreeSelect!:any

    models:any ={
        structure:{
            title:'',
            subTitle:'',
            monthId:'',
            id:router.currentRoute.query.id,
            categoryId:'',
        },
        common: {
            id:'',
            title:'',
            headCode:[],
            endCode:[],
            data:[]
        },
        dataCodeType:[],
        selectDeptId:'',
        surveyForm: {...commonSurveyStr},
        surveyFormArr:  {...commonSurveyArr},
        dynamicForm:{...commonSurveyStr},
        surveyInfo: [],
        commonExt:{
            id:'',
            title:'',
            headCode:[],
            endCode:[]
        },
        dynamic: {
            id:'',
            title:'',
            headCode:[],
            endCode:[],
            dynamicTitle:[],
            dynamicDefineData:[],
            dynamicDataList:[],
            lastDataList:[],
        }
    }

  
    
    options:any ={
        commonData:{},
        codeNumbers:['01','02','03','04','05','06'],
        selectParams:{
            clearable: true,
            placeholder: '请选择'
        },
        treeParams:{
            clickParent: true,
            filterable: true,
            accordion: true,
            data: [],
            props: {
                children: 'children',
                label: 'label',
                disabled: 'disabled',
                value: 'id'
            }
        }
    }

  searchAreaFun(value: any): void {
    this.areaTreeSelect.filterFun(value);
  }

  findStructure(){
        getStructureById({id:this.models.structure.id}).then(res =>{
            if(res.data){
                this.models.structure.title = res.data && res.data.title;
                this.models.structure.subTitle = res.data && res.data.subTitle;
                this.models.structure.monthId = res.data && res.data.monthId +'';
                this.models.structure.categoryId = res.data && res.data.categoryId +'';
            }
        }).catch(e =>{
            console.error(e);
        });
    }

    deduceCodeType(contentType,code,value): boolean {
        if(contentType === value){
            this.models.dataCodeType[code] = contentType;
            return true;
        }
        return false;
    }

    surveyInfo(){
        surveyByStructureId({id:this.models.structure.id}).then(res =>{
            if(res.data){
                this.models.surveyInfo = res.data;
                this.buildSurveyInfo();
                this.queryCommonData();
            }
        }).catch(e =>{
            console.error(e);
        });
    }

    extractSuerveyData(){
        if(this.models.surveyInfo && this.models.surveyInfo.length > 0){
            this.models.common = this.models.surveyInfo[0];
            if(this.models.surveyInfo.length > 1){
                this.models.dynamic = this.models.surveyInfo[1];
                this.models.dynamic.lastDataList=[];
                this.models.dynamic.dynamicTitle = JSON.parse(this.models.dynamic.dynamicTitle);
            }
        }
    }

    queryCommonData(){
        queryLastData({
            structureId: this.models.structure.id,
            subStructureId: this.models.common.id,
            dynamicSubStructureId: this.models.dynamic? this.models.dynamic.id: '',
            departId: this.models.selectDeptId
        }).then(res =>{
            this.options.commonData = res.data;
            if(!this.options.commonData){
                return;
            }
            this.options.codeNumbers.forEach(cn =>{
                const headPrefix = 'head';
                const endPrefix  = 'end';
               
                if(this.options.commonData[headPrefix+cn] && this.options.commonData[headPrefix+cn] != null){
                    this.models.surveyForm[headPrefix+cn] = this.options.commonData[headPrefix+cn];
                }
                if(this.options.commonData[endPrefix+cn] && this.options.commonData[endPrefix+cn] != null){
                    this.models.surveyForm[endPrefix+cn] = this.options.commonData[endPrefix+cn];
                }
            })
    
            Object.keys(this.models.dataCodeType).forEach(code =>{
                const value = this.models.dataCodeType[code];
                switch(value){
                    case '0':
                        this.models.surveyForm.investData[code] = this.options.commonData[code];
                        break;
                    case '1':
                        this.models.surveyFormArr.investData[code] = [this.options.commonData[code]];
                        break;
                    case '2':
                         if(this.options.commonData[code]){
                            if(this.options.commonData[code].includes(';')){
                                this.models.surveyFormArr.investData[code] =this.options.commonData[code].split(';');
                            }else{
                                this.models.surveyFormArr.investData[code] = [this.options.commonData[code]];
                            }
                         }
                      
                        break;
                }
            })
            if(this.options.commonData.dynamicDataList){
                this.models.dynamic.lastDataList =this.options.commonData.dynamicDataList;
               
                const oneData = this.models.dynamic.lastDataList[0];
                this.options.codeNumbers.forEach(cn =>{
                    const headPrefix = 'head';
                    const endPrefix  = 'end';
                
                    if( oneData[headPrefix+cn]){
                        this.models.dynamicForm[headPrefix+cn] = oneData[headPrefix+cn];
                    }
                    if(oneData[endPrefix+cn]){
                        this.models.dynamicForm[endPrefix+cn] = oneData[endPrefix+cn];
                    }
                })
            }

        }).catch(e =>{
            console.error(e);
        });
    }
    
    dynamicSubStructureHandler(val:any){
   
       if(val && val.length >0){
            this.models.dynamic.dynamicDataList = val.map(obj => {
                const { id, ...rest } = obj;
                return rest;
            });
       }
    
     }

    buildSurveyInfo(){
      this.extractSuerveyData();
    }

    pickerOptions= {
        disabledDate(time) {
        return time.getTime() > Date.now();
        },
        shortcuts: [{
        text: '今天',
        onClick(picker) {
            picker.$emit('pick', new Date());
        }
        }, {
        text: '昨天',
        onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
        }
        }, {
        text: '一周前',
        onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
        }
        }]
    }

    handleClick(event) {
      event.preventDefault();
    }
    getUserAreaInfo(){
        userAreaTreeSelectData().then(res =>{
            if(res.data){
                this.options.treeParams.data = res.data;
                if(this.areaTreeSelect){
                    this.areaTreeSelect.treeDataUpdateFun(res.data);
                }
              
            } 
        }).catch(e =>{
            console.error(e);
        })
    }
    mounted(){
        if(!this.models.structure.id){
            this.$router.push('/bus/surveySearch');
            return;
        }
        this.findStructure();
        this.surveyInfo();
        this.options.selectParams.placeholder='请选择区域';
        
    }
    handleSubmit(){

        this.$confirm('确定要提交调查数据码？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        }).then(() => {
             //    for (let key in this.models.surveyFromArr.investData) {

             //       let dt = this.models.surveyFromArr.investData[key];
             //       if(dt.length > 0){
             //         this.models.surveyFrom.investData[key] = dt.join(';');
             //       }
             //    }
            for (let key in this.models.surveyFormArr.updateData) {

                let dt = this.models.surveyFormArr.updateData[key];
                if(dt.length > 0){
                    this.models.surveyForm.updateData[key] = dt.join(';');
                }
            }
            this.models.surveyForm.structureId = this.models.structure.id;
            this.models.surveyForm.categoryId  = this.models.structure.categoryId;
            this.models.surveyForm.title  = this.models.structure.title;
            this.models.surveyForm.subTitle  = this.models.structure.subTitle;
            this.models.surveyForm.subStructureId  = this.models.common.id;
    
            //动态表单收集数据
            if(this.models.dynamic && this.models.dynamic.id && this.models.dynamic.dynamicDataList && this.models.dynamic.dynamicDataList.length > 0){
                
    
                this.models.surveyForm.dynamicList = this.models.dynamic.dynamicDataList;
           
               
                this.models.surveyForm.dynamicList.forEach((dynamicData:any) =>{

                    dynamicData.structureId = this.models.structure.id;
                    dynamicData.subStructureId = this.models.dynamic.id;
                    this.options.codeNumbers.forEach(cn =>{
                        const headPrefix = 'head';
                        const endPrefix  = 'end';
                       
                        if(this.models.dynamicForm[headPrefix+cn]){
                            dynamicData[headPrefix+cn] = this.models.dynamicForm[headPrefix+cn];
                        }
                        if(this.models.dynamicForm[endPrefix+cn]){
                            dynamicData[endPrefix+cn] = this.models.dynamicForm[endPrefix+cn];
                        }
                    })
                })

            }
           
            return addFromOnline(this.models.surveyForm);
        }).then((response: any) => {
            this.$message.success("数据提交成功");
        }).catch((e) => {
            console.error(e);
        });
    }
    findOriginData(){
        console.log("a")
    }
    beforeMount(){
        this.initModels();
        this.getUserAreaInfo();
    }

    initModels(){
        this.models.surveyForm = {...commonSurveyStr};
        this.models.surveyFormArr =  {...commonSurveyArr};
        this.models.dynamicForm ={...commonSurveyStr};
        this.models.dynamic = {
            id:'',
            title:'',
            headCode:[],
            endCode:[],
            dynamicTitle:[],
            dynamicDefineData:[],
            dynamicDataList:[]
        };
    }
   
}
</script>
<style>
.textCenter{
    text-align: center;
}
.headerTitle{
    margin-left: 80px;
    margin-bottom: 5px;
}

.bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #f8f9fc;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .inputLabel{
    color: #303133;
   
  }
  

</style>